package com.greenphosphor.glasshouse;

import java.io.*;
import java.net.*;
import java.util.logging.*;

public class CICPProducer {

  public String prov_url = null;
  public String prov_host = null;
  public int prov_port = 0;
  public boolean isPerma = false;
  public PermaClient pc = null;
  private Logger log = null;
  private boolean permaWait = false;

  public CICPProducer ( String inUrl ) {
    prov_url = inUrl;
    log = Logger.getLogger("cicp");
  }

  public CICPProducer ( String inHost, int inPort ) {
    prov_host = inHost;
    prov_port = inPort;
    log = Logger.getLogger("cicp");
  }

  public String getResponse ( String msg ) throws IOException, InterruptedException {
    String rline = null;
    String[] split = msg.split(",");
    if ( !isPerma && split.length >= 3 && split[2].equals("-5") ) {
      if ( permaWait ) {
        log.info("permaWait is on");
        return "ok";
      }
      log.info("bringing up permaclient socket");
      Socket s = new Socket("localhost", 5544);
      pc = new PermaClient(s);
      Thread t = new Thread(pc);
      pc.myThread = t;
      t.start();
      isPerma = true;
    }
    if ( isPerma ) {
      if ( pc.isBusy ) {
        log.info("permaclient is busy");
        rline = "ok";
      }
      else {
        //log.info("sending message to permaclient socket");
        rline = pc.doMessage(msg);
      }  
    }
    else {
      permaWait = true;
      if ( prov_url != null ) {
        String strUrl = prov_url + "msg=" + msg;
        URL url = new URL(strUrl);
        //log.info("prov_url {" + prov_url + "}");
        BufferedReader bir = new BufferedReader(new InputStreamReader(url.openStream()));
        rline = bir.readLine();
        bir.close();
      }
      else {
        Socket s = new Socket(prov_host, prov_port);
        s.setSoTimeout(5000);
        PrintWriter pwg = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        try {
          pwg.println(msg);
          pwg.flush();
          rline = br.readLine();
          pwg.close();
          br.close();
          log.info("received from gateway: " + rline);
        }
        catch ( IOException ie ) {
          log.info("io error talking to producer: " + ie);
        }
        finally {
          s.close();
        }
      }
      permaWait = false;
    }
    return rline;
  }
}
